import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { IStateType, ILoignResultType, ILoginFormType } from '@/typings/userType'
import { doUserLogin } from '@/api/userApi'

/* export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
}) */

const useUserStore = defineStore('user', {
  persist: {
    storage: window.sessionStorage
  },
  state: () =>
  ({
    userinfo: {
      uid: 0,
      username: '',
      token: ''
    }
  } as IStateType),
  getters: {
    token: state => state.userinfo.token || ''
  },
  actions: {
    setUserInfo(info: ILoignResultType) {
      this.userinfo = info;
    },
    async fetchLoginAction(userData: ILoginFormType) {
      let ret = await doUserLogin(userData)
      if (ret.code === 0) {
        this.setUserInfo(ret.data)
      }
      return ret.code

    }
  }
})
export type userStoreType = ReturnType<typeof useUserStore>
export default useUserStore

